#!/usr/bin/env python
# encoding: utf-8
__author__ = 'Zjay '
"""
@version: 3.6.3
@author: Zjay 
@license: Apache Licence 
@site: 
@software: PyCharm
@file: package_sqlalchemy.py
@time: 2017/12/12 11:22
"""

import sqlalchemy as sqlorm

print(sqlorm.__version__)

from sqlalchemy.orm import sessionmaker, relationship, backref
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import ForeignKey
from sqlalchemy import Column, Integer, String, create_engine

Base = declarative_base()

"""定义基类"""


class User(Base):
    __tablename__ = 'users'

    id = Column(String(50), primary_key=True)
    email = Column(String(50))
    name = Column(String(50))
    addresses = relationship("Address", order_by="Address.id", backref="user")


class Address(Base):
    __tablename__ = 'addresses'

    id = Column(Integer, primary_key=True)
    email_address = Column(String, nullable=False)
    user_id = Column(Integer, ForeignKey('users.id'))
    user = relationship("User", backref=backref('addresses', order_by=id))

    def __repr__(self):
        return "<Address(email_address='%s')>" % self.email_address


# 初始化数据库连接:
engine = create_engine('mysql+pymysql://www-data:www-data@127.0.0.1:3306/awesome')
# 创建DBSession类型:
DBSession = sessionmaker(bind=engine)
session = DBSession()
userlist = session.query(User).all()
print(len(userlist))
print(userlist[0].name)
user = userlist[0]
user.addresses = [Address(email_address='jack@google.com'), Address(email_address='j25@yahoo.com')]
session.add(user)
session.commit()